package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import com.itheima.service.ExprService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Resource
    private DeptService deptService;
    @Resource
    private ExprService exprService;

    @Override
    public PageResult<Emp> queryPage(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("create_time"));
        //链式查询与参数condition构造条件查询器实现动态sql
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);
        //只查询有员工的部门，性能更优
        //存在没有部门的员工，需要过滤掉null值
        Set<Integer> deptIds = page.getRecords().stream().map(Emp::getDeptId).filter(Objects::nonNull).collect(Collectors.toSet());
        if(!CollectionUtils.isEmpty(deptIds)) {
            Map<Integer, String> deptMap = deptService.listByIds(deptIds).stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            page.getRecords().forEach(r -> {
                Integer deptId = r.getDeptId();
                r.setDeptName(deptMap.get(deptId));
            });
        }
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        List<EmpExpr> exprList = emp.getExprList();
        save(emp);
        //还要给expr判空以及设置员工id
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(er -> er.setEmpId(emp.getId()));
            exprService.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEmps(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("批量删除员工数量不能为空");
        }
        //直接用条件构造器
        exprService.remove(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId,ids));
////        //当exprList为null时会报错，但前端中exprList初始为空列表，新增工作经历会往其中加入一个{}expr对象，因此应该可以不考虑exprlist为null的情况
////        List<Integer> empExprIds = listByIds(ids).stream().flatMap(e -> e.getExprList().stream().map(EmpExpr::getId)).toList();
//        removeBatchByIds(ids);
//        if (!CollectionUtils.isEmpty(empExprIds)) {
//            exprService.removeBatchByIds(empExprIds);
//
//        }
    }

    @Override
    public Emp getEmp(Integer id) {
        Emp emp = getById(id);
        List<EmpExpr> exprList = exprService.list(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id));
        emp.setExprList(exprList);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        updateById(emp);
        List<EmpExpr> exprList = emp.getExprList();
        exprService.remove(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId,emp.getId()));
        if(!CollectionUtils.isEmpty(exprList)){
            //需要给工作经历设置empId
            Integer empId = emp.getId();
            exprList.forEach(e->e.setEmpId(empId));
            exprService.saveBatch(exprList);
        }
    }

    @Override
    public List<Emp> all() {
        List<Emp> empList = new ArrayList<>();
        empList=list();
        if(!CollectionUtils.isEmpty(empList)){
            List<Integer> empIds = empList.stream().map(Emp::getId).toList();
            List<EmpExpr> empExprList = exprService.list(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, empIds).groupBy(EmpExpr::getEmpId));
            empList.forEach(e->{
                Integer id = e.getId();
                List<EmpExpr> exprList = empExprList.stream().filter(er -> Objects.equals(er.getEmpId(), e.getId())).toList();
                e.setExprList(exprList);
            });
        }

        return empList;
    }
}
